/**
 * huize Service Inc
 * All Rights Reserved @2018
 */
package com.huize.zhike.framework.common.page;


import com.huize.zhike.framework.common.enumeration.ErrorEnum;
import com.huize.zhike.framework.common.exception.BizException;

import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * PageFetcher分页数据提取器
 *
 * @author tianyuliang
 * @version $Id: PageFetcher.java, v0.1 2018/10/15
 */
public class PageFetcher {

    /**
     * 分页数据提取
     *
     * @param condition     分页条件
     * @param counter       count计算方法
     * @param listFetcher   列表数据获取
     * @param dataConverter 数据转换，通常是DTO列表转换为VO列表
     * @param <T>           输入列表类型
     * @param <R>           输出列表类型
     * @return
     * @throws BizException
     */
    public static <T, R> Page<R> fetchPageData(PageCondition condition, Supplier<Long> counter, Supplier<List<T>> listFetcher, Function<List<T>, List<R>> dataConverter) throws BizException {
        if (condition == null) {
            condition = new PageCondition.Builder().build();
        }
        Long count = counter.get();
        if (count == null || count == 0) {
            return Page.ofEmpty(condition.getPageSize());
        }
        List<T> originData = listFetcher.get();
        if (dataConverter == null) {
            throw new BizException(ErrorEnum.DATA_CONVERTER_NULL_OBJECT);
        }
        return new Page<R>(condition.getPageNum(), condition.getPageSize(), count.intValue(), dataConverter.apply(originData));
    }

}
